package com.itheima.goods.controller;

import com.itheima.goods.pojo.Goods;
import entity.Result;
import entity.StatusCode;
import org.apache.catalina.session.StandardSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public Result findAll(@RequestBody Map searchMap) {
        searchMap.put("token", UUID.randomUUID());

        return new Result(true, StatusCode.OK, "登录成功", searchMap);
    }


    @GetMapping("/info")
    public Result findUser(String token) {
        Map searchMap = new HashMap();
        searchMap.put("name", "admin");
        searchMap.put("roles", Arrays.asList("admin", "user"));
        searchMap.put("avatar", "admin");
        return new Result(true, StatusCode.OK, "查询成功", searchMap);
    }

    @PostMapping("/logout")
    public Result logout(@RequestBody Map searchMap) {
        return new Result(true, StatusCode.OK, "退出成功", searchMap);
    }

    @RequestMapping("/save")
    public Goods saveSession(HttpSession session) {
        System.out.println(session instanceof StandardSession);
        Goods goods = new Goods();
        goods.setName("手机");
        goods.setBrand("华为");
        session.setAttribute("goods", goods);
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(HttpSession.class));
        this.redisTemplate = redisTemplate;
        redisTemplate.opsForValue().set("session", session);

        HttpSession session1 = (HttpSession) redisTemplate.opsForValue().get("session");

        return (Goods) session1.getAttribute("goods");
    }
}
